//
//  KZTestResultVC.m
//  听说弱点强化训练
//
//  Created by 朱凯 on 2018/10/24.
//  Copyright © 2018年 盛超. All rights reserved.
//

#import "KZTestResultVC.h"

// view
#import "KZTestResultInfomationView.h"
#import "KZStarView.h"
#import "KZRainView.h"
// vc
#import "KZVocabularyImproveLookFailuresVC.h"
#import "KZVocabularyImproveMakeTestVC_version2.h"
#import "LSResPackageController.h"
#import "LSWrongCheckViewController.h"

// api
#import "KZVocabularyImproveNetApi.h"
#import "LSResListManager.h"
#import "LSFtpManager.h"

@interface KZTestResultVC ()

@property (nonatomic, strong) KZTestResultInfomationView *infomationView;
@property (nonatomic, strong) UIImageView *bgView;
@property (nonatomic, strong) UIImageView *waveView;
// 合格
@property (nonatomic, strong) KZStarView *starView;
@property (nonatomic, strong) UIImageView *flowerView;
// 不合格
@property (nonatomic, strong) UIImageView *cryView;
@property (nonatomic, strong) KZRainView *rainView;

@property (nonatomic,strong) LSSoundPlayer *soundPlayer;

@end

@implementation KZTestResultVC
{
    BOOL _isSuccess;
    
    BOOL _isGoToLookFailures;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    self.view.backgroundColor = [UIColor colorWithWhite:0.95 alpha:1];
    [self setupNaviUI];
    [self setupUI];
    _isGoToLookFailures = false;
}
- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    [self setNaviAttributeWithTranslucent:true stateBarLightContent:true];
    if (_isGoToLookFailures) {
        [_rainView startRain];
        _isGoToLookFailures = false;
    }
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [_rainView stopRain];
}


#pragma mark - 视图
- (void)setupNaviUI {

    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [backButton setImage:[UIImage imageNamed:@"kz-关闭"] forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    [backButton sizeToFit];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
}
- (void)setupUI {
    
    // 背景和波浪是都有的
    _bgView = [UIImageView new];
    _bgView.image = [UIImage imageNamed:@"kz-结果背景"];
    [self.view addSubview:_bgView];
    [_bgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.bottom.equalTo(@0);
    }];
    _waveView = [UIImageView new];
    _waveView.image = [UIImage imageNamed:@"kz-结果波纹"];
    [_bgView addSubview:_waveView];
    [_waveView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(@0);
        make.height.equalTo(_waveView.mas_width).multipliedBy(539.0/750);
    }];
    
    // 结果视图也都有
    WeakObj(self);
    _infomationView = [KZTestResultInfomationView new];
    if (_packageModel) {
        _infomationView.packageModel = _packageModel;
    } else {
        _infomationView.resultDic = _resultDic;
    }
    _infomationView.clickBlock = ^(int func) {
        [selfWeak infomationViewClick:func];
    };
    [self.view addSubview:_infomationView];
    [_infomationView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(W(10));
        make.right.mas_equalTo(W(-10));
        make.top.equalTo(self.view.mas_centerY).multipliedBy(0.6);
        if (@available(ios 11.0,*)) {
            make.bottom.equalTo(self.view.mas_safeAreaLayoutGuideBottom).offset(W(-10));
        } else {
            make.bottom.mas_equalTo(W(-10));
        }
    }];
    
    // 分析是否成功
    BOOL isSuccess = true;
    __block NSInteger failureCount = 0;
    if (_packageModel) {
        
        [_packageModel.currentPackage.Detail enumerateObjectsUsingBlock:^(KZVocabularyCurrentPackageDetailModel * _Nonnull model, NSUInteger idx, BOOL * _Nonnull stop) {
            if (model.IsPassed.boolValue == false) {
                failureCount ++;
            }
        }];
        
        if (failureCount < 16) {
            isSuccess = true;
        } else {
            isSuccess = false;
        }
        
     } else {
         NSInteger failureCount = ((NSNumber*)[_resultDic objectForKey:@"WrongCount"]).integerValue;
         if (failureCount>0) {
             isSuccess = false;
         }
     }

    _isSuccess = isSuccess;
    
    // 成功
    if (_isSuccess) {
        //[KZSoundTool playSound:KZSoundType_result_success];
        LSSoundPlayer *player = [[LSSoundPlayer alloc] initWithSound:KZSoundType_result_success];
        self.soundPlayer = player;
        
        _starView = [[KZStarView alloc] initWithStars:(19 - failureCount) / 4];
        [self.view addSubview:_starView];
        [_starView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(@0);
            make.bottom.equalTo(_infomationView.mas_top);
            make.left.right.equalTo(@0);
        }];
        
        _flowerView = [UIImageView new];
        _flowerView.alpha = 0;
        _flowerView.image = [UIImage imageNamed:@"kz-撒花"];
        [self.view insertSubview:_flowerView belowSubview:_infomationView];
        [_flowerView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.equalTo(self.view);
            make.height.equalTo(_flowerView.mas_width);
            make.centerY.equalTo(_infomationView.mas_top);
            make.centerX.equalTo(self.view);
        }];
    } else {
        //[KZSoundTool playSound:KZSoundType_result_failure];
        LSSoundPlayer *player = [[LSSoundPlayer alloc] initWithSound:KZSoundType_result_failure];
        self.soundPlayer = player;
        
        _cryView = [UIImageView new];
        [self.view insertSubview:_cryView belowSubview:_infomationView];
        [_cryView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.width.equalTo(self.view);
            make.height.equalTo(_cryView.mas_width).multipliedBy(241.0/750);
            make.bottom.equalTo(_infomationView.mas_top);
        }];
        
        _rainView = [KZRainView new];
        [self.view insertSubview:_rainView belowSubview:_cryView];
        [_rainView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(_bgView);
        }];
    }
    
    
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self startAnimation];
    });
}

- (void)startAnimation {
    
    [UIView animateWithDuration:0.8 delay:0 usingSpringWithDamping:1 initialSpringVelocity:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
        [_bgView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.bottom.mas_equalTo(H(-250));
        }];
        [self.view layoutIfNeeded];
    } completion:^(BOOL finished) {
        if (_isSuccess) {
            _flowerView.transform = CGAffineTransformMakeScale(0.1, 0.1);
            [UIView animateWithDuration:0.5 animations:^{
                _flowerView.alpha = 1;
                _flowerView.transform = CGAffineTransformIdentity;
            }];
        } else {
            [_cryView gif:@"kz-哭泣" repeat:false];
            [_rainView startRain];
        }
    }];
}

#pragma mark - Net，听说词汇和生词接口几乎一样，首次进入不会调用查询接口，只有点击下个包才会调用
#pragma mark ------- 听说词汇
// 获取听说词汇包信息
- (void)getListenSayVocabularyPackageInfo {
    
    [MBProgressHUD showLoadind:@"正在查询待下一个听说词汇包，请稍候..."];
    
    KZVocabularyImproveNetApi *api = [KZVocabularyImproveNetApi new];
    api.requestParam = @{@"stageNo":KGetUserDefaults(@"TestLayer"),
                         @"schoolId":DR_UserInfo.SchoolID,
                         @"stuId":DR_UserInfo.UserID,};
    [api getListenSayVocabularyPackageInfo:^(KZVocabularyPackageModel *model) {
        
        [MBProgressHUD hideHud];
        
        KZVocabularyImproveMakeTestVC_version2 *vc = [KZVocabularyImproveMakeTestVC_version2 new];
        vc.type = _type;
        vc.packageModel = model;
        [self.navigationController pushViewController:vc animated:true];
        
    } failuer:^(NSString *error) {
        [MBProgressHUD showFailureWithText:error];
    }];
}
#pragma mark ------- 生词
// 获取听说词汇包信息
- (void)getUnfamiliarVocabularyPackage {
    
    [MBProgressHUD showLoadind:@"正在查询待下一生词包，请稍候..."];
    
    KZVocabularyImproveNetApi *api = [KZVocabularyImproveNetApi new];
    api.requestParam = @{@"stageNo":KGetUserDefaults(@"TestLayer"),
                         @"schoolId":DR_UserInfo.SchoolID,
                         @"stuId":DR_UserInfo.UserID,};
    [api getUnfamiliarVocabularyPackage:^(KZVocabularyPackageModel *model) {
        
        [MBProgressHUD hideHud];
        
        KZVocabularyImproveMakeTestVC_version2 *vc = [KZVocabularyImproveMakeTestVC_version2 new];
        vc.type = _type;
        vc.packageModel = model;
        [self.navigationController pushViewController:vc animated:true];
        
    } failuer:^(NSString *error) {
        
        [MBProgressHUD showFailureWithText:error];
    }];
}

#pragma mark - 事件
- (void)back {
    [self deleteAllUnZip];
    [self.navigationController popToRootViewControllerAnimated:true];
    
}
- (void)infomationViewClick:(int)func {
    
    // 听说词汇的
    if (_packageModel) {
        
        switch (func) {
            case 0: // 下一个词汇包
            {
                // 保存本包内容，并请求下一个包的内容
                if (_type == KZVocabularyTypeLS) {
                    [self getListenSayVocabularyPackageInfo];
                } else {
                    [self getUnfamiliarVocabularyPackage];
                }
            }
                break;
            case 1: // 查看不合格词汇
            {
                _isGoToLookFailures = true;
                NSMutableArray *temp = [NSMutableArray new];
                for (int i = 0; i < _packageModel.currentPackage.Detail.count; i ++) {
                    KZVocabularyCurrentPackageDetailModel *model = _packageModel.currentPackage.Detail[i];
                    if (!model.IsPassed.boolValue) {
                        [temp addObject:model];
                    }
                }
                KZVocabularyImproveLookFailuresVC *vc = [KZVocabularyImproveLookFailuresVC new];
                vc.failureModels = temp.copy;
                [self push:vc];
            }
                break;
            case 2: // 关闭窗口
                [self back];
                break;
                
            default:
                break;
        }
        
    }
    
    
    // 听力和朗读的按钮点击
    else {
        switch (func) {
            case 0: // 下一关\ 重新作答
            {
                [self deleteAllUnZip];
                [self reloadData];
            }
                break;
            case 1: // 查看错题
            {
                NSLog(@"查看错题");
                [self enterWrongQuesVC];
            }
                break;
            case 2: // 关闭窗口
                [self back];
                break;
            default:
                break;
        }
    }
    
}

- (void)reloadData {
    LSResListManager *manager = [[LSResListManager alloc] init];
    NSDictionary *dict = @{@"StuID":DR_UserInfo.UserID,
                           @"StageNo":KGetUserDefaults(@"TestLayer"),
                           @"SchoolID":KGetUserDefaults(@"SchoolID"),
                           @"TypeID":[_resultDic objectForKey:@"PackageTypeID"],
                           @"UpdateTime":@""
                           };
    
    manager.requestParam = @{@"DictString":[NSObject objectToJson:dict]};
    WeakObj(self);
    [manager requestWithCompltionSuccess:^(LSModelLSResList *model) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            LSResPackageController *vc = [[LSResPackageController alloc] init];
            vc.model = model;
            [selfWeak.navigationController pushViewController:vc animated:YES];
        });

    } failuer:^(NSString *error) {
        
        NSLog(@"重新刷新数据错误");
        
    }];
}

- (void)enterWrongQuesVC {
    
    LSWrongCheckViewController *vc = [[LSWrongCheckViewController alloc] init];
    vc.speedLayer = self.wrongCheckModel.speedLayer;
    vc.allAnswerDict = self.wrongCheckModel.allAnswerDict;
    vc.wrongQuesIndexArr = self.wrongCheckModel.wrongQuesIndexArr;
    vc.wrongQuesModelArr = self.wrongCheckModel.wrongQuesModelArr;
    vc.wrongQuesItemArr = self.wrongCheckModel.wrongQuesItemArr;
    vc.typeIDarr = self.wrongCheckModel.typeIDarr;

    [self push:vc];
}

- (void)deleteAllUnZip {
    for (NSInteger i = 0; i<_reslistModel.ResItemList.count; i++) {
        NSString *fileName = _reslistModel.ResItemList[i].QuesID;
        LSFtpManager *manager = [[LSFtpManager alloc] init];
        [manager deleteUnzip:fileName];
    }
    NSString *unzipPath = [NSString stringWithFormat:@"%@%@", NSHomeDirectory(),@"/Documents/record"];
    NSDirectoryEnumerator *enumerator = [[NSFileManager defaultManager] enumeratorAtPath:unzipPath];
    for (NSString *name in enumerator) {
        [[NSFileManager defaultManager] removeItemAtPath:[unzipPath stringByAppendingPathComponent:name] error:nil];
    }
    NSLog(@"资源全部删除");
}

@end
